package com.android.manghe.user.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.base.tools.codec.MD5
import com.android.manghe.R
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.user.presenter.PReg
import com.fm.openinstall.OpenInstall
import kotlinx.android.synthetic.main.activity_reg.*
import java.util.*


class RegActivity : MVPActivity<PReg>() {

    private var mIsPswVisible = false
    private val TotalCount = 60L * 1000

    private var isBind = false

    companion object {
        fun showActivity(context: Context, giftAmount: String?, requestCode: Int) {
            val intent = Intent(context, RegActivity::class.java)
            giftAmount?.let {
                intent.putExtra("giftAmount", it)
            }
            (context as Activity).startActivityForResult(intent, requestCode)
        }

        fun showActivity(
            context: Context,
            avatar: String,
            openId: String,
            type: String,
            nickName: String,
            requestCode: Int
        ) {
            val intent = Intent(context, RegActivity::class.java)
            intent.putExtra("avatar", avatar)
            intent.putExtra("openId", openId)
            intent.putExtra("type", type)
            intent.putExtra("nickName", nickName)
            (context as Activity).startActivityForResult(intent, requestCode)
        }
    }


    override fun getLayoutId() = R.layout.activity_reg

    override fun initData(savedInstanceState: Bundle?) {
        p.giftAmount = intent.getStringExtra("giftAmount")

        p.avatar = intent.getStringExtra("avatar")
        p.openid = intent.getStringExtra("openId")
        p.type = intent.getStringExtra("type")
        p.nickName = intent.getStringExtra("nickName")
        titleBar.setToolbar(if (!TextUtils.isEmpty(p.type)) "绑定手机号码" else "注册")
            .setLeftIcon(R.mipmap.icon_back_black).hideBottomLine()
            .setTitleAndStatusBgColor(R.color.white)
        newPicCode()
        if (!TextUtils.isEmpty(p.type)) {
            layoutLogin.visibility = View.GONE
            layoutPsw.visibility = View.GONE
            isBind = true
        }

        initListener()

        p.getInviteMsg()
    }

    private fun newPicCode() {
        val ivPicCode = ImageView(this)
        layoutPicCode.addView(ivPicCode)
        p.scodeToken = MD5.convertString(UUID.randomUUID().toString())
        GlideHelper.loadNoCache(
            this,
            ConstantsUrl.domain + ConstantsUrl.MEMBERWELCOMSCODE + "?scode_token=${p.scodeToken}",
            ivPicCode
        )
        ivPicCode.setOnClickListener {
            layoutPicCode.removeAllViews()
            newPicCode()
        }
    }

    private fun initListener() {

        layoutLogin.setOnClickListener {
            finish()
        }
        ivEye.setOnClickListener {
            changePswVisible()
        }
        tvDoc.setOnClickListener {
            //用户服务协议
            SimpleWebViewActivity.showActivity(
                mContext,
                "https://www.manghe98.com/protocol/user_service.html",
                "用户服务协议",
                false
            )
        }
        tvSecret.setOnClickListener {
            //隐私政策
            SimpleWebViewActivity.showActivity(
                mContext,
                "https://www.manghe98.com/protocol/privacy.html",
                "隐私政策",
                false
            )
        }
        tvSendCode.setOnClickListener {
            val tel = etTel.text.toString().trim()
            if (TextUtils.isEmpty(tel)) {
                ToastUtil.showShort(this@RegActivity, "请输入您的手机号")
                return@setOnClickListener
            }
            val picCode = etPicCode.text.toString().trim()
            if (TextUtils.isEmpty(picCode)) {
                ToastUtil.showShort(this@RegActivity, "请输入图形验证码")
                return@setOnClickListener
            }
            showLoadingDialog()
            p.sendCode(tel, picCode)
        }
        etTel.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                ivX.visibility = if (etTel.text.toString().isNotEmpty()) View.VISIBLE else View.GONE
            }

        })

        ivX.setOnClickListener {
            etTel.setText("")
        }
        btnReg.setOnClickListener {
            val tel = etTel.text.toString().trim()
            val psw = if (isBind) "kanjia123456" else etPsw.text.toString()
            val code = etCode.text.toString().trim()
            if (TextUtils.isEmpty(tel)) {
                ToastUtil.showShort(this@RegActivity, "请输入手机号码")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(psw)) {
                ToastUtil.showShort(this@RegActivity, "请输入密码")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(code)) {
                ToastUtil.showShort(this@RegActivity, "请输入验证码")
                return@setOnClickListener
            }
            if (!checkBox.isChecked) {
                ToastUtil.showShort(this@RegActivity, "请阅读并同意用户服务协议")
                val shake: Animation = AnimationUtils.loadAnimation(
                    applicationContext, R.anim.shake
                )
                layoutAgreement.startAnimation(shake)
                return@setOnClickListener
            }
            showLoadingDialog()
            p.reg(tel, psw, code)
        }
    }

    private fun changePswVisible() {
        etPsw.transformationMethod =
            if (mIsPswVisible) PasswordTransformationMethod.getInstance() else HideReturnsTransformationMethod.getInstance()
        mIsPswVisible = !mIsPswVisible
        ivEye.setImageResource(if (mIsPswVisible) R.mipmap.visible else R.mipmap.invisible)
    }

    fun regOk() {
//        val tm = getSystemService(Service.TELEPHONY_SERVICE) as TelephonyManager
//        TuiAManager.send(this, MD5.md5(tm.getDeviceId()), 5)
        OpenInstall.reportRegister()
        if (TextUtils.isEmpty(p.type)) {
            val intent = Intent()
            intent.putExtra("tel", etTel.text.toString())
            intent.putExtra("psw", etPsw.text.toString())
            setResult(Activity.RESULT_OK, intent)
        } else {
            val intent = Intent()
            intent.putExtra("bindType", p.type)
            intent.putExtra("tel", etTel.text.toString())
            intent.putExtra("psw", "kanjia123456")
            setResult(Activity.RESULT_OK, intent)
        }
        finish()
    }

    fun regFail(text: String?) {
        ToastUtil.showShort(
            this,
            if (TextUtils.isEmpty(text)) (if (TextUtils.isEmpty(p.type)) "注册失败" else "绑定失败") else text
        )
    }

    fun closeLoadingDialog() {
        hideLoadingDialog()
    }

    fun sendCodeOk() {
        startCountDown()
    }

    fun sendCodeFail(text: String?) {
        ToastUtil.showShort(this, if (TextUtils.isEmpty(text)) "发送验证码失败" else text)
    }

    private var mTimer: CountDownTimer? = null
    private fun startCountDown() {
        mTimer = object : CountDownTimer(TotalCount, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                tvSendCode.text = "${(millisUntilFinished / 1000)}s"
                tvSendCode.isClickable = false
            }

            override fun onFinish() {
                tvSendCode.text = "发送验证码"
                tvSendCode.isClickable = true
            }
        }
        mTimer!!.start()
    }

    private fun stopCountDown() {
        mTimer?.let {
            it.cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopCountDown()
    }
}